import 'package:inmotion_pro/extension/future_error_handler.dart';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:inmotion_pro/pages/mixin/cache_mixin.dart';
import 'package:inmotion_pro/pages/mixin/http_request_mixin.dart';
import 'package:inmotion_pro/pages/mixin/realtime_info_mixin.dart';
import 'package:inmotion_pro/pages/models/vehicle_model.dart';
import 'package:get/get.dart';
import 'package:inmotion_pro/routes/app_routes.dart';
import 'package:inmotion_pro/service/vehicle_connection_service.dart';
import 'package:inmotion_pro/service/global_service.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

import 'state.dart';

// 车辆列表控制器
class VehicleListController extends GetxController
    with HttpRequestMixin, CacheMixin, RealtimeInfoMixin {
  // 状态
  final VehicleListState state = VehicleListState();

  @override
  void onInit() {
    super.onInit();
  }

  onRefresh() async {
    httpRequestMixinOnlyRequestAuthorizedVehicleList()
        .then((vehicleList) async {
      // 先显示车辆列表，提升用户体验
      state.vehicleList.value = GlobalService.to.cacheVehicleList.toList();
      state.vehicleList.refresh();
      cacheMixinAuthorizedVehicleWriteToCache(vehicleList);
    });
    return Future.value();
  }

  // 进入车主申请列表
  toAuthorizedUsersOnTap(VehicleModel model) {
    if (model.isOwner.value != true) return;
    Get.toNamed(AppRoutes.VEHICLE_AUTH_USER_LIST, arguments: model);
  }

  // 删除本地车辆
  deleteLocalVehicleOnTap(VehicleModel model) {
    LxAlert.show(
      local.confirm_to_delete_vehicle,
      title: local.prompt_title,
      confirmTitle: local.delete,
      cancelTitle: local.cancel,
      confirmCallback: (_) {
        // 停止轮询获取车辆实时数据
        realtimeInfoMixinStopLoopToGetVehicleRealTimeData()
            .then((success) async {
          if (success) {
            VechileConnectionService.to.bluetoothConnectHelper!.disconnect().then((_) {
              cacheMixinDeleteCacheVehicle(model.bleName).then((success) {
                if (success) {
                  state.vehicleList.value =
                      GlobalService.to.cacheVehicleList.toList();
                  Loading.showSuccess(local.deleting_successful);
                } else {
                  Loading.showError(local.deleting_failed);
                }
              });
            });
          } else {
            Loading.showError(local.logout_failed);
          }
        }).catchErrorHandler();
      },
    );
  }
}
